'use strict';
/**
 * @fileoverview 玩家科技信息
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var mongoose = require('mongoose');
var MarketItemSchema = require('./marketItemSchema.js');
var constantUtil = require('../../util/constantUtil');
var marketConf = require('../../config/marketConf');
var mgrUtil = require('../../util/mgrUtil');
var eventType = require('../../consts/eventType.js');

var marketSchema = new mongoose.Schema({
    // 角色id
    role_id: {
        type: Number,
        required: true,
        unique: true,
        index: true
    },

    // 市场物品列表，市场配置表ID
    market_list: [MarketItemSchema],

    // 剩余免费次数
    free_times: {
        type: Number,
        default: 0
    },

    // VIP免费次数
    vip_free_times: {
        type: Number,
        default: 0
    },

    // 收费刷新次数
    refresh_times: {
        type: Number,
        default: 0
    },

    // 市场数据等级（当前数据在市场多少级时生成）
    market_data_lv: {
        type: Number,
        default: 0
    }
});

/**
 * 增加市场免费刷新次数
 * @return {[type]} [description]
 */
marketSchema.methods.addFreeNum = function (num) {
    this.free_times += num;
};

/**
 * 获取vip免费次数
 * @return {[type]} [description]
 */
marketSchema.methods.getVipNum = function () {
    return this.vip_free_times;
};

/**
 * 设置vip免费次数
 * @return {[type]} [description]
 */
marketSchema.methods.setVipNum = function (num) {
    this.vip_free_times = (+num);
};

/**
 * 替换市场物品
 * @param  {[type]} market_pos  [位置]
 * @param  {[type]} market_item [物品]
 * @return {[type]}     [description]
 */
marketSchema.methods.replaceItem = function (market_pos, market_item) {
    var ref_item = this.market_list[market_pos];
    if (!ref_item) {
        return false;
    }
    ref_item.market_id = market_item.market_id;
    ref_item.discount = market_item.discount;

    return true;
};

var market_rate_info = marketConf.getMarketRateInfo();
var market_rate = market_rate_info.market_rate;
var total_prob = market_rate_info.total_prob;

/**
 * 按随机概率值，查找市场物品ID
 */
var _findIdByRateVal = function (lvl, rate_val) {
    var market_id = _.find(market_rate_info[lvl].market_rate, function (rate_item) {
        return rate_item.sum_rate > rate_val;
    }).market_id;
    return market_id;
};

/**
 * 检查市场数据等级，如果低于市场建筑等级，则刷新市场物品列表
 */
marketSchema.methods.checkDataLvl = function (lvl) {
    if (lvl > this.market_data_lv) {
        this.market_data_lv = lvl;
        this.randMarketList();
        return true;
    }
    return false;
};

/**
 * 随机生成市场物品列表
 */
marketSchema.methods.randMarketList = function () {
    /*
     * 从市场配置表取出ID列表转成数组
     * 循环生成市场物品
     */
    var rand_market_item_list = [];
    var lvl = this.market_data_lv;
    var market_item_cnt = constantUtil.value('market_goods_num');
    var range = market_rate_info[lvl].total_prob;
    for (var i = 0; i < market_item_cnt; i++) {
        var rand_val = _.random(range - 1);
        var market_id = _findIdByRateVal(lvl, rand_val);
        var market_item = marketConf.findByID(lvl, market_id);
        var discount = 100;
        if (market_item.cost_type === 2) {
            discount = _randDiscount();
        }

        rand_market_item_list.push({
            market_pos: i,
            market_id: market_id,
            discount: discount
        });
    }

    this.market_list = rand_market_item_list;
};

/**
 * 随机生成市场指定位置物品
 */
marketSchema.methods.randMarketPos = function (market_pos) {
    var lvl = this.market_data_lv;
    var range = market_rate_info[lvl].total_prob;
    var rand_val = _.random(range - 1);
    var market_id = _findIdByRateVal(lvl, rand_val);

    var market_item = marketConf.findByID(lvl, market_id);
    var discount = 100;
    if (market_item.cost_type === 2) {
        discount = _randDiscount();
    }

    this.market_list[market_pos].market_id = market_id;
    this.market_list[market_pos].discount = discount;

    return this.market_list[market_pos];
};

/**
 * 生成随机折扣
 */
var _randDiscount = function () {
    var disc_array = marketConf.getMarketDiscountArray();
    var total_prob = 0;
    _.some(disc_array, function (disc_info) {
        total_prob += disc_info.probability;
    });

    var rand_num = _.random(total_prob - 1);
    var check_prop = 0;
    for (var i = 0; i < disc_array.length; i++) {
        check_prop += disc_array[i].probability;
        if (rand_num < check_prop) {
            return disc_array[i].discount;
        }
    }

    return 100;
};

marketSchema.pre('save', function (next) {
    this.increment();
    if (!this.isNew && !!this.isModified()) {
        this.pushModify();
    }
    next();
});

/**
 * 获取修改
 * @return {[type]} [description]
 */
marketSchema.methods.getLastChange = function () {
    // var change_info = this.toJSON();
    // delete change_info.role_id;
    // delete change_info.market_list;
    // delete change_info.vip_free_times;
    // delete change_info.refresh_times;
    // delete change_info.market_data_lv;
    // return change_info;

    var ret = {};
    ret.free_times = this.free_times;
    return ret;
};

/**
 * 推送给用户
 * @return {[type]} [description]
 */
marketSchema.methods.push = function () {
    this.pushModify();
};

marketSchema.methods.pushModify = function () {
    var self = this;
    mgrUtil.sendStatusMessage(
        [self.role_id],
        eventType.ON_MARKET_CHANGE,
        self.getLastChange(),
        function (err, fails) {
            if (err) {
                console.error('send arena message error: %j, fail ids: %j', err, fails);
                return;
            }
        }
    );
};

if (!marketSchema.options.toJSON) {
    marketSchema.options.toJSON = {};
}
/* jshint unused:false */
marketSchema.options.toJSON.transform = function (doc, ret) {
    delete ret.role_id;
    delete ret.market_list;
    delete ret.vip_free_times;
    delete ret.refresh_times;
    delete ret.market_data_lv;

    delete ret._id;
    delete ret.__v;
};
mongoose.model('Market', marketSchema);
